package stu.jiajia.servlet;

import org.apache.commons.beanutils.BeanUtils;
import stu.jiajia.bean.Human;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * Servlet implementation class Form
 */
@WebServlet("/register")
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Human human = form2Bean(req, resp);
            req.setAttribute("human", human);
            req.getRequestDispatcher("/pages/success.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private Human form2Bean(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        Human human = new Human();
        BeanUtils.populate(human, req.getParameterMap());
        return human;
    }
}
